<template>

  <div class="box">
    <h1>身高体重详细分布情况</h1>
    <div class="chart1" ref="rightCenterChart1"></div>
    <div class="chart2" ref="rightCenterChart2"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { getRightCenterData, getRightCenterMainData } from '@/api/data-screen/right-charts';

onMounted(() => {
  getChartData1();
  getChartData2();

})

let data1 = ref([])
let data0 = ref([])
async function getChartData1() {
  try {
    // 并行请求优化
    const [res1, res0] = await Promise.all([
      getRightCenterData(1),
      getRightCenterData(0)
    ])

    // 正确赋值响应式变量
    data1.value = formattingData(res1.data)
    data0.value = formattingData(res0.data)

    // 确保数据就绪后初始化图表
    initRightCenterChart()

  } catch (error) {
    console.error('数据获取失败:', error)
    // 可添加重试逻辑
  }
}


async function getChartData2() {
  try {
    // 并行请求优化
    getRightCenterMainData().then(result => {
      console.log(result)
      initRightCenterChartMain2(result.data)
    })


  } catch (error) {
    console.error('数据获取失败:', error)
    // 可添加重试逻辑
  }
}


// 格式化后端返回的数据（增强版）
function formattingData(originalData) {
  if (!originalData || !Array.isArray(originalData)) {
    console.error('Invalid data format');
    return [];
  }

  return originalData
    .filter(item => {
      if (!item) {
        // console.warn('发现空数据项');
        return false;
      }
      return !isNaN(item.height) && !isNaN(item.weight);
    })
    .map(item => [Number(item.height), Number(item.weight)]);
}

//右中散点图
const rightCenterChart1 = ref<HTMLElement | null>(null);
const rightCenterChart2 = ref<HTMLElement | null>(null);


let rightCenterChartInstance: echarts.ECharts | null = null;
const initRightCenterChart = () => {
  if (rightCenterChart1.value) {
    rightCenterChartInstance = echarts.init(rightCenterChart1.value);
    updateRightCenterChart();
  }
}
const updateRightCenterChart = () => {
  try {
    type EChartsOption = echarts.EChartsOption;
    var option: EChartsOption;

    option = {
      color: ['#FF69B4', '#00BFFF'],
      backgroundColor: 'rgba(70, 130, 180, 0.15)', // 钢蓝透明背景
      grid: {
        top: '10%',
        left: '2%',
        right: '6.9%',
        bottom: '15%',
        containLabel: true
      },
      textStyle: {
        fontSize: '10',
        color: '#ccc'
      },
      tooltip: {
        // trigger: 'axis',
        showDelay: 0,
        //图标单位
        formatter: function (params: any) {
          if (params.value.length > 1) {
            return (
              params.seriesName +
              ' :<br/>' +
              params.value[0] +
              'cm ' +
              params.value[1] +
              'kg '
            );
          } else {
            return (
              params.seriesName +
              ' :<br/>' +
              params.name +
              ' : ' +
              params.value +
              'kg '
            );
          }
        },
        axisPointer: {
          show: true,
          type: 'cross',
          lineStyle: {
            type: 'dashed',
            width: 1,
            color: '#ccc'
          }
        }
      },
      //图例
      legend: {
        data: ['女', '男'],
        left: 'center',
        bottom: 20,
        textStyle: {
          color: '#ccc',
          fontSize: 12
        }
      },
      xAxis: [
        {
          type: 'value',
          scale: true,
          axisLabel: {
            formatter: '{value} cm'
          },
          splitLine: {
            show: false
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          scale: true,
          axisLabel: {
            formatter: '{value} kg'
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(173, 216, 230, 0.1)' // 淡蓝色辅助线
            }
          },
        }
      ],
      series: [
        {
          name: '女',
          type: 'scatter',
          symbolSize: 5,//散点大小
          emphasis: {
            focus: 'series'
          },
          // prettier-ignore
          data: data0.value,
          markArea: {
            silent: true,
            itemStyle: {
              color: 'transparent',
              borderWidth: 1,
              borderType: 'dashed'
            },
          },
          //最大值标
          markPoint: {
            symbol: 'pin',
            symbolSize: 45,
            label: {
              show: true, // 是否显示标签
              //formatter: '{b}', // 标签内容，{b} 表示数据名称
              color: 'black', // 标签文字颜色
              fontSize: 12 // 标签文字大小
            },
            data: [
              { type: 'max', name: '最大体重' },
              { type: 'max', name: '最大身高', valueDim: 'x' }
            ]
          },
          //平均值
          markLine: {
            lineStyle: {
              type: 'solid',
              //color: '#fff'
            },
            label: {
              show: true,
              position: 'end',
              color: '#fff', // 平均值数值颜色为白色
              fontSize: 12
            },
            data: [
              { type: 'average', name: '平均体重' },
              { type: 'average', name: '平均身高', valueDim: 'x' }] // 标记平均身高
          }
        },
        {
          name: '男',
          type: 'scatter',
          symbolSize: 5,
          emphasis: {
            focus: 'series'
          },


          // prettier-ignore
          data: data1.value,
          markArea: {
            silent: true,
            itemStyle: {
              color: 'transparent',
              borderWidth: 1,
              borderType: 'dashed'
            },
          },
          //最大值标
          markPoint: {
            symbol: 'pin',
            symbolSize: 40,
            label: {
              show: true, // 是否显示标签
              //formatter: '{b}', // 标签内容，{b} 表示数据名称
              color: 'black', // 标签文字颜色
              fontSize: 10 // 标签文字大小

            },
            data: [
              { type: 'max', name: '最大体重' },
              { type: 'max', name: '最大身高', valueDim: 'x' }
            ]
          },
          markLine: {
            lineStyle: {
              type: 'solid',
              //color: '#fff' // 平均值线颜色
            },
            label: {
              show: true,
              position: 'end',
              color: '#fff', // 平均值数值颜色为白色
              fontSize: 11
            },
            data: [{ type: 'average', name: '平均体重' },
            { type: 'average', name: '平均身高', valueDim: 'x' }]// 标记平均身高
          }
        }
      ]
    };
    option && rightCenterChartInstance.setOption(option);
  } catch (error) {
    console.log("右中散点图获取数据失败！")
  }
}


const colorMap = {
  "BMI<17": {
    colorStops: [
      { offset: 0, color: '#ff9500' },
      { offset: 1, color: '#dbb403' }
    ]
  },
  "17≤BMI<17.5": {
    colorStops: [
      { offset: 0, color: '#dbb403' },
      { offset: 1, color: '#89e484' }
    ]
  },
  "17.5≤BMI<24": {
    colorStops: [
      { offset: 0, color: '#89e484' },
      { offset: 1, color: '#51e628' }
    ]
  },
  "24≤BMI<30": {
    colorStops: [
      { offset: 0, color: '#51e628' },
      { offset: 1, color: '#f5ed05' }
    ]
  },
  "BMI≥30": {
    colorStops: [
      { offset: 0, color: '#f5ed05' }, // 起始颜色（顶部）
      { offset: 1, color: '#e43111' }  // 结束颜色（底部）[[7]]
    ]
  }
};

function initRightCenterChartMain2(data1) {
  console.log(data1)
  if (!rightCenterChart2.value) return;
  const myChart = echarts.init(rightCenterChart2.value);

  const series = data1.map(item => ({
    name: item.scope, // 将 scope 映射为 name
    type: 'bar',
    stack: 'bmi',     // 保持堆叠分组
    data: item.data,  // 直接使用接口中的 data 数组
    color: colorMap[item.scope] || '#ccc', // 动态匹配颜色，未匹配则用默认色
    label: {          // 统一标签样式
      show: true,
      fontSize: 12,
      color: '#000000',
      fontStyle: 'italic'
    }
  }));

  // 2. 预计算总和
  console.log(data1)
  const totalMale = data1.reduce((sum, item) => sum + item[0], 0);
  const totalFemale = data1.reduce((sum, item) => sum + item[1], 0);
  // 3. 创建总和 series 项
  const totalSeries = {
    name: '总和',
    type: 'bar',
    stack: 'bmi',
    label: {
      show: true,
      position: 'right',
      distance: 20, // 调整标签位置避免重叠
      formatter: () => '', // 清空默认文本
      rich: {
        total: {
          color: '#fff',
          fontSize: 16,
          lineHeight: 24,
          padding: [5, 10],
          backgroundColor: 'rgba(0,0,0,0.5)',
          // 直接注入预计算值
          content: `男生总数：${totalMale}\n女生总数：${totalFemale}`
        }
      }
    },
    data: [0, 0]
  };
  // 4. 合并 series 数组
  const finalSeries = [...series, totalSeries];
  console.log(finalSeries)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
      }
    },
    legend: {
      data: ['BMI<17', '17≤BMI<17.5', '17.5≤BMI<24', '24≤BMI<30', 'BMI≥30'],
      bottom: '10%',   // 右侧图例位
      textStyle: { color: '#fff', fontSize: 16 }
    },
    grid: {
      left: '3%',
      right: '4%',
      top: "0%",
      containLabel: true
    },
    xAxis: {
      type: 'value',
      splitLine: {
        show: false // 隐藏网格线避免干扰
      },
      axisLabel: {
        show: true,
        // 刻度标签文字的颜色
        color: '#fff'

      },
    },
    yAxis: {
      type: 'category',
      data: ['男生BMI分布', '女生BMI分布'],
      axisLabel: {
        show: true,
        // 刻度标签文字的颜色
        color: '#fff',

      },
    },

    series: series

  };
  myChart.setOption(option);
}


</script>

<style scoped>
.box {
  height: 100%;
  width: 100%;
  align-items: center;
  justify-content: center;
}

.chart1 {
  height: 60%;
  width: 100%;
}

.chart2 {
  height: 30%;
  width: 100%;
}

h1 {
  text-align: center;
  color: aliceblue;
  margin: 0;
  margin-top: 1rem;
  padding: 0;
}
</style>